﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace winform服务端
{
    public partial class 客户端 : Form
    {
        public 客户端()
        {
            InitializeComponent();
        }
        Socket clientSocket;
        private void button1_Click(object sender, EventArgs e)
        {
            //创建连接对象
           
            clientSocket = new Socket(AddressFamily.InterNetwork,
                SocketType.Stream, 
                ProtocolType.Tcp);

            //链接
            clientSocket.Connect(IPAddress.Parse(textBox1.Text),int.Parse(textBox2.Text));
            textBox3.Text = "与服务器连接成功";
            //接受线程
            Thread receivetThread=new Thread((obj) =>
            {
                Socket receiveThreadsSocket = obj as Socket;
                byte[] bs=new byte[1024];
                int len = 0;
                while ((len=receiveThreadsSocket.Receive(bs))>0)
                {
                    textBox3.Invoke(new Action<string>(s =>
                    {
                        textBox3.Text += s + "\r\n";

                    }), Encoding.UTF8.GetString(bs, 0, len));
                }

            });
            receivetThread.IsBackground = true;
            receivetThread.Start(clientSocket);
        }

        private void 客户端_FormClosing(object sender, FormClosingEventArgs e)
        {
            clientSocket.Shutdown(SocketShutdown.Both);
            clientSocket.Close();
            clientSocket.Dispose();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (clientSocket!=null)
            {
                clientSocket.Send(Encoding.UTF8.GetBytes(textBox4.Text));
            }
        }
    }
}
